package com.woniuxy.his.component;

import com.woniuxy.his.common.JwtUtils;
import com.woniuxy.his.entity.User;
import com.woniuxy.his.mapper.UserMapper;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;

@Slf4j
public class ShiroRealm extends AuthorizingRealm {

    @Resource
    private UserMapper userMapper;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {

        //principal为return new SimpleAuthenticationInfo
        // (user,user.getPassword(),user.getUsername())里面的第一个参数user

        User user=(User)principal.getPrimaryPrincipal();
        log.info("user为：{}",user);
        //
        log.info("userid为：{}",user.getUserId());
        List<String> roles = userMapper.findRole(user.getUserId());
        List<String> permissions = userMapper.findPermissions(user.getUserId());

        //返回值封装
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        //设置角色
        info.setRoles(new HashSet<>(roles));
        //权限
        info.setStringPermissions(new HashSet<>(permissions));
        return info;

    }

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        log.info("登录操作：{}",token);
        JwtToken jwtToken = (JwtToken) token;
        System.out.println("8888888888888888888888");
        //从token中解析出jwt附带的数据，如果jwt过期会抛出异常
        User user = JwtUtils.parseJwt(jwtToken.getToken());



        return new SimpleAuthenticationInfo(user,jwtToken.getToken(),getName());
    }

}
